//
//  NestViewController.swift
//  JXPagingView
//
//  Created by jiaxin on 2018/11/2.
//  Copyright © 2018 jiaxin. All rights reserved.
//

import UIKit
import MTCategory
import JXPagingView
import JXCategoryView
import JXSegmentedView
import RxSwift
import RxCocoa
import YPNavigationBarTransition

class NestViewController: BaseViewController {
    var naviDataSource = JXSegmentedTitleDataSource()
    lazy var naviSegmentedView = JXSegmentedView()
    lazy var listContainer = JXSegmentedListContainerView(dataSource: self, type: .scrollView)

    var lists: [JXSegmentedListContainerViewListDelegate?] = []
    
    private lazy var provider: MTProvider<MTClubApi> = {
        let provider = MTProvider<MTClubApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    let userProvider: MTProvider = MTProvider<UserCenterApi>()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let titles = ["我的俱乐部", "俱乐部大厅"]
        naviDataSource.titles = titles
        naviDataSource.itemSpacing = 0
        naviDataSource.itemContentWidth = 80
        naviDataSource.titleNormalColor = UIColor.text.x9b9b9b
        naviDataSource.titleSelectedColor = UIColor.text.x1d1a1a
        naviDataSource.isTitleZoomEnabled = true
        naviDataSource.titleNormalFont = PingFangSCSemiboldFont(16)
        naviDataSource.titleSelectedFont = PingFangSCSemiboldFont(16)

        naviSegmentedView.contentEdgeInsetLeft = 15
        naviSegmentedView.contentEdgeInsetRight = 15
        naviSegmentedView.frame = CGRect(x: 0, y: 0, width: 240, height: 30)
        naviSegmentedView.dataSource = naviDataSource
        
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorColor = UIColor.text.x1d1a1a
        indicator.indicatorWidth = 20
        indicator.indicatorHeight = 3
        naviSegmentedView.indicators = [indicator]

        navigationItem.titleView = naviSegmentedView

        view.addSubview(listContainer)

        naviSegmentedView.listContainer = listContainer
        
        setupNavigationBar()
        
        NotificationCenter.default.addObserver(self, selector: #selector(NestViewController.selectChatIndex), name: GlobalNotificationName.didPushChat.name, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func selectChatIndex() {
        naviSegmentedView.selectItemAt(index: 0)
    }
    
    lazy var createClubBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("创建", for: .normal)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        if let image: UIImage = UIImage.init(color: UIColor(hex: 0xffc000), size: CGSize(width: 60, height: 24))?.byRoundCornerRadius(12) {
            btn.setBackgroundImage(image, for: .normal)
            btn.addTarget(self, action: #selector(queryUserMoney), for: .touchUpInside)
        }
        return btn
    }()
    
    private func setupNavigationBar() {
        let item = UIBarButtonItem(customView: createClubBtn)
        navigationItem.rightBarButtonItems = [item]
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        listContainer.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
}

extension NestViewController {
    
    // MARK: - 创建俱乐部
    @objc private func queryUserMoney() {
        /// 查询创建俱乐部所需要消耗的钻石
        MTClubTool.config(provider: provider, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            guard let groupMoney = model?.result?.groupMoney else { return }
            let userMoney = model?.result?.moeny ?? 0
            //let wechatOfficeAccount = model?.result?.wechatOfficeAccount ?? ""
            if model?.code == 200, userMoney < groupMoney {
                //创建专属俱乐部需花费\(groupMoney)钻石您当前余额不够，是否去充值
                UIAlertController.rx.show(in: weakSelf, title: "提示", message: "创建俱乐部需要\(groupMoney)钻石，钻石不足，请充值", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                    /// 去充值的引导
                    if index == 1 {
                        if UserDefaults.AppValidate.isValidate.storedBool == false {
                            let c = MTPaymentViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        } else {
                            let c = MTInAppPurchasesViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        }
                    }
                })
                .disposed(by: globalDisposedBag)
            } else {
                /// 跳转去创建俱乐部
                UIAlertController.rx.show(in: weakSelf, title: "提示", message: "创建专属俱乐部需花费\(groupMoney)钻石是否去创建?", buttons: [.cancel("取消"), .default("去创建")]).subscribe(onSuccess: { [weak self] index in
                    guard let weakSelf = self else { return }
                    if index == 1 {
                        let createVC = MTCreateClubViewController { (needRefrence) in
                            /// 创建成功拉取数据
                            //weakSelf.loadFirst()
                            self?.naviSegmentedView.reloadData()
                        }
                        weakSelf.navigationController?.pushViewController(createVC, animated: true)
                    }
                })
                .disposed(by: globalDisposedBag)
            }
        }) { (error) in
            
        }
    }
    
}

extension NestViewController: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return 2
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        if index == 0 {
            if lists.first != nil {
                return lists.first!!
            }
            let mineClub: MTMineClubViewController = MTMineClubViewController()
            lists.append(mineClub)
            return mineClub
        }
        if lists.count > 1 && lists.last != nil {
            return lists.last!!
        }
        let pagingVC = NestSubjectViewController()
        pagingVC.nestContentScrollView = listContainer.scrollView
        pagingVC.pagingView.listContainerView.isCategoryNestPagingEnabled = true
        lists.append(pagingVC)
        return pagingVC
    }
}

extension NestViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
